package org.dromara.hm.mapper.saleOrder;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dromara.hm.domain.HmSaleOrderPickUp;
import org.dromara.hm.domain.vo.saleOrder.HmSaleOrderPickUpVo;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;

import java.util.List;

/**
 * 销售订单提货、回款Mapper接口
 *
 * @author Hzy
 * @date 2025-01-06
 */
public interface HmSaleOrderPickUpMapper extends BaseMapperPlus<HmSaleOrderPickUp, HmSaleOrderPickUpVo> {

    @Select("SELECT sop.* " +
        "FROM hm_sale_order_pick_up sop " +
        "JOIN hm_sale_order so ON sop.sale_order_id = so.sale_id " +
        "JOIN ( " +
        "    SELECT sale_order_id, SUM(pick_up_num) AS total_pick_up_num " +
        "    FROM hm_sale_order_pick_up " +
        "    WHERE pick_up_type = '1' " +
        "    GROUP BY sale_order_id " +
        ") subquery ON sop.sale_order_id = subquery.sale_order_id " +
        "WHERE so.sale_product_id = #{productId} " +
        "  AND sop.pick_up_type = 0 " +
        "  AND subquery.total_pick_up_num < so.sale_num")
    List<HmSaleOrderPickUp> getUnfinishedOrdersByProductId(@Param("productId") Long productId);


    @Update("UPDATE hm_sale_order_pick_up SET pick_up_quantity = pick_up_quantity - #{reduceQuantity} WHERE id = #{id}")
    void reducePickUpQuantity(@Param("id") Long id, @Param("reduceQuantity") Integer reduceQuantity);

    /**
     * 查询补充提货记录并将其映射为 HmSaleOrderPickUpVo 格式。
     * 用于在提货记录列表中统一显示。
     *
     * @param originalSaleId 原始销售订单ID
     * @param isCommercialProductFilter 是否过滤商品产品 (true/false/null)
     * @param isGiftProductFilter 是否过滤赠品产品 (true/false/null)
     * @return 映射后的提货记录列表
     */
    List<HmSaleOrderPickUpVo> selectSupplementaryPickupsAsNormalPickups(
        @Param("originalSaleId") Long originalSaleId,
        @Param("isCommercialProductFilter") Boolean isCommercialProductFilter,
        @Param("isGiftProductFilter") Boolean isGiftProductFilter
    );
}
